from config import db, login_manager
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from twittor.models.Tweet import Tweet as T
import re
import pprint

followers = db.Table('followers',
                     db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),  # 关注者
                     db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))  # 被关注者
                     )


class User(db.Model, UserMixin):
    __tablename__ = "user"
    __table_args__ = {'mysql_engine': 'InnoDB'}  # 设置表的存储引擎为InnoDB
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment="用户id")
    username = db.Column(db.String(64), unique=True, index=True, nullable=False, comment="用户名称")
    email = db.Column(db.String(64), unique=True, index=True, comment="用户邮箱")
    password_hash = db.Column(db.String(128), nullable=False, comment="用户密码")
    img_name = db.Column(db.String(255), comment="头像图片的名字")
    img_path = db.Column(db.String(255), comment="头像图片的路径")
    about_me = db.Column(db.String(255), comment="用户介绍")
    create_time = db.Column(db.DateTime, default=datetime.utcnow)

    Tweet = db.relationship('Tweet', backref="author", lazy="dynamic")

    followerd = db.relationship(
        'User', secondary=followers,
        primaryjoin=(followers.c.follower_id == id),
        secondaryjoin=(followers.c.followed_id == id),
        backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')

    # 新手笔记：primaryjoin 参数指定了关联表（followers）中的哪一列与被关联表（User）的主键相匹配
    # followerd对应的是secondaryjoin

    def __repr__(self):
        return 'id={},username={},email={},password_hash={}'.format(
            self.id, self.username, self.email, self.password_hash
        )

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def is_following(self, user):
        return self.followerd.filter(followers.c.followed_id == user.id).count() > 0

    def follow(self, user):
        if not self.is_following(user):
            self.followerd.append(user)

    def unfollow(self, user):
        if self.is_following(user):
            self.followerd.remove(user)

    def myself_Tweets(self):
        return T.query.filter(T.userid == self.id).order_by(T.create_time.desc())

    # 热门和关注的博客
    def popular_and_followed_Tweets(self):
        # 包含没有关注推荐热门的数据
        popular_data = T.query.order_by(T.views.desc(), T.create_time.desc()).limit(5)

        followed = T.query.join(followers, followers.c.followed_id == T.userid).filter(
            followers.c.follower_id == self.id)
        own = T.query.filter(T.userid == self.id)
        followed_data = followed.union(popular_data).union(own).order_by(T.views.desc(), T.create_time.desc())
        return followed_data


# load_user函数是从session中加载用户对象的方法。
# 当用户登录时，Flask-Login会自动调用这个函数，并将返回的用户对象设置为当前用户。
@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))